const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoClient = require('mongodb').MongoClient;
const session = require('express-session');

const dbUrl = "mongodb://127.0.0.1:27017/"

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie:{
        maxAge:1000*60*30
    },
    rolling:true
}));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
 
// parse application/json
app.use(bodyParser.json());

app.set('view engine','ejs');
app.use(express.static('public'));

app.use((req,res,next)=>{
    if(req.url=="/login"||req.url=="/doLogin"){
        next();
    }else{
        if(req.session.userInfo&&req.session.userInfo.username!=""){
            app.locals['userInfo'] = req.session.userInfo;
            next();
        }else{
            res.redirect('/login')            
        }
    }
});

app.get('/', (req, res) => {
    res.send('hello world!');
});

app.get('/login', (req, res) => {
    res.render('login');
});

app.get('/product', (req, res) => {
    res.render('product');
});

app.get('/productadd', (req, res) => {
    res.render('productadd');
});

app.get('/productedit', (req, res) => {
    res.render('productedit');
});
app.get('/productdelete', (req, res) => {
    res.send('delete Product!');
});

app.get('/logOut', (req, res) => {
    req.session.destroy((err)=>{
        if(err){
            console.log(err);
            return false;
        }else{
            res.redirect('/login');
        }
    });

});

app.post('/doLogin', (req, res) => {
    //console.log(req.body);

    mongoClient.connect(dbUrl,(err,client)=>{
        if(err){
            console.log(err);
            return false;
        }

        let db = client.db('productmanage');
        let result = db.collection('user').find(req.body);

        result.toArray((error,data)=>{
            if(data.length>0){
                req.session.userInfo = data[0];
                console.log(req.session.userInfo);
                res.redirect('/product');               
            }else{
                res.send("<script>alert('登陆失败');location.href='/login'</script>");
            }
            client.close();
        });
    })
});

app.listen(8080);